package com.topisv.tms.web.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.enums.StatusEnums;

public class BaseController {
	protected Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	
	/**
	 * 根据用户权限查找商户组以及仓库
	 * @param model
	 * @param customerCode
	 */
	public void fillSelectValue(Model model, String customerCode) {
		// 查找商户组
		ShiroUser curUser = getShiroUser();
		model.addAttribute("customerList", customersService.loadCustomerByAuthority(curUser));

		List<AreaGroup> warehouseList = null;
		if (StringUtils.isNotBlank(customerCode)) {
			warehouseList = this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
		} else {
			if (StatusEnums.user_type_customer.getStatus().equals(curUser.userType)) {
				warehouseList = areaGroupService.loadAreaGroupByAuthority(curUser, curUser.customerCode);
			} else if (StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)) {
				warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
			}
		}
		model.addAttribute("warehouseList", warehouseList);
	}
	/**
	 * 取出Shiro中的当前用户
	 */
	public ShiroUser getShiroUser() {
		return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	}
	/**
     * 
     * 将json对象写入响应流
     * 
     * @param json
     * @param response [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     * @author zhangpeijun
     */
    public void writeJsonToResponse(JSONObject json, HttpServletResponse response) {
        if (null != response) {
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(null != json ? json.toString() : "");
            } catch (IOException e) {
                log.error(null != json ? "Method param = " + json.toString() : "Method param json is null");
                log.error("Write json To response IOException", e);
            } finally {
                if (null != out) {
                    out.close();
                }
            }
        }
    }
}
